package com.tanhua.admin.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.MovementsVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ManageService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private MovementApi movementApi;

    /**
     * 分页查询mysql数据中的userinfo
     */
    public PageResult users(Integer page, Integer pagesize) {
        //1、调用userInfoApi分页查询用户数据，ipage（数据列表，总数）
        IPage iPage = userInfoApi.findAll(page,pagesize);
        //2、构造返回
        return new PageResult(page,pagesize,iPage.getTotal(),iPage.getRecords());
    }

    public UserInfo findUserById(Long userId) {
        return userInfoApi.findById(userId);
    }

    //根据用户id，查询视频列表
    public PageResult findVideosByUserId(Long uid, Integer page, Integer pagesize) {
        //调用API，分页查询视频列表 -- items中存放的List<Video>
        PageResult result = videoApi.findByUserId(uid,page,pagesize); //返回结果：list和总数
        //获取视频列表
        List<Video> items = (List<Video>) result.getItems();
        //查询视频列表是否存在
        if(CollUtil.isEmpty(items)) {
            return result;
        }
        UserInfo userInfo = userInfoApi.findById(uid);
        //一个Video转化一个VideoVo
        List<VideoVo> list = new ArrayList<>();
        for (Video video : items) {
            VideoVo vo = VideoVo.init(userInfo, video);//动态发布人的userinfo。video对象
            list.add(vo);
        }
        //构造返回
        result.setItems(list);
        return result;
    }

    /**
     * 查询动态列表
     */
    public PageResult findMovements(Long uid, Integer status, Integer page, Integer pagesize) {
        //1、调用API查询动态列表 PageResult  -- items -- List<Movement>
        PageResult result = movementApi.findMovements(uid,status,page,pagesize);
        //2、获取动态列表
        List<Movement> items = (List<Movement>) result.getItems();
        //3、查询动态列表是否存在
        if(CollUtil.isEmpty(items)) {
            return result;
        }
        //4、一个Movement转化一个MovementVo
        List<MovementsVo> list = new ArrayList<>();
        for (Movement item : items) {
            Long userId = item.getUserId(); //动态发布人
            UserInfo userInfo = userInfoApi.findById(userId); //动态发布人详情
            MovementsVo vo = MovementsVo.init(userInfo, item);//动态发布人详情，动态对象
            list.add(vo);
        }
        //5、构造返回
        result.setItems(list);
        return result;
    }
}
